define(["../common"], function() {
	
	
	var $form = $("#form_addOrEdit");
	var formCfg = {
		rules: {
			hasHomeNum: function(element) {
				return $(element).val().indexOf("栋") >= 0 || $(element).val().indexOf("号") >= 0;
			}
		},
		 messages: {
			 hasHomeNum: "{0}应包含楼号房号"
		 },
		fields: {
			alias: "地址名称: length[~50]",
			street: "街道地址: required;length[~80];hasHomeNum",
			postalCode: "邮编: postcode",
			consignee: "收货人: required;length[2~20]",
			mobile: "手机号: required;mobile",
			tel: "tel"
		}
	};
	
	requirePlugin(["validator"],function() {
		$form.validator(formCfg);
	});
	
	// 初始化表单值
	$.getJSON(g_userDomain + "/address/one4Edit/json" + Common.getUrlParams(), function(data) {
		if (data.status !== 0) {
			$(document).failMsg(data.message);
			return;
		}
		
		var address = data.result;
		
		// (添加)
		if (!address) {
			// 地区表单赋默认值
			Region.locating(function(region) {
				loadRegions(region.regionId);
			});
			return;
		}
		
		// (编辑)给表单赋值
		$form.initData(address);
		var regionId = address.region.regionId;
		loadRegions(regionId);
		
	});
	
	// 提交完成表单
	$form.on('valid.form', function(e, form) {
		if (!$form.lock()) return;
		
		$form.loadMsg("正在保存...");
		$.post(g_userDomain + "/address/addOrEditDo/json", $form.serialize(), function(data){
			if (data.status !== 0) {
				$form.failMsg(data.message);
				return;
			}
			$form.infoMsg("保存成功");
			setTimeout(function() {
				location.href = g_userDomain + "/address";
			},2000);
		});

	});
	
	function loadRegions(regionId) {
		require(["region"], function() {
			$("#regions").regionsSelect({
				value: regionId, 
				onLoad: function($select) {
					$select.attr("data-rule","地区: required;");
					$select.addClass("form-control");
					$select.css({width: "48%",float: "left","margin-right": "1%"});
				},
				onSelect: function($select) {
					$("#regionId").val($select.val());
					var regionName = $("[id^='selectRegion_'] option:selected").map(function(){
						return $(this).text();
					}).get().join("");
					$("#regionName").val(regionName);
				}
			});
		});
	}	
});